package com.example.mybatis.service.impl;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.net.URLEncodeUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.example.mybatis.bean.QuestionBan;
import com.example.mybatis.mapper.QuestionBanMapper;
import com.example.mybatis.service.FileService;

import com.example.mybatis.utils.ResultUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.ClassUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service
@Slf4j
public class FileImpl implements FileService {

    @Resource
    QuestionBanMapper questionBanMapper;

    //
    public ResultUtil upload(MultipartFile file, HttpServletRequest request) {
        String filePath = ClassUtils.getDefaultClassLoader().getResource("static/image").getPath();

        //重命名文件名称
        //获取原名称
        String fileName = file.getOriginalFilename();
        //获取文件后缀名
        String suffix = fileName.substring(fileName.lastIndexOf("."));

        fileName = String.format("%s%s", IdUtil.simpleUUID(), suffix);
        //存储文件
        try {
            file.transferTo(new File(String.format("%s/%s", filePath, fileName)));
            return ResultUtil.ok().put("fileName", "/image/" + fileName);
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return ResultUtil.error("上传文件失败");

    }


    public ResultUtil upload(MultipartFile file) {
        return null;
    }

    @Override
    public ResultUtil delete(String fileName) {
        return null;
    }


    public ResultUtil readExcel(MultipartFile file, Integer detailsId) {
        //判断文件后缀名
        String fileName = file.getOriginalFilename();
        if (!fileName.endsWith("xls")
                && !fileName.endsWith("xlsx")) {
            return ResultUtil.error("文件格式不正确");
        }
        ExcelReader reader = null;
        try {
            reader = ExcelUtil.getReader(file.getInputStream());

        } catch (IOException e) {
            e.printStackTrace();
            log.error("上传失败，原因：{}", e.getMessage());
            return ResultUtil.error("上传失败");

        }

        //读取
       // List<Map<String, Object>> dataList = reader.readAll();
        List<List<Object>> dataList = reader.read();
        System.out.println(dataList);
        if(dataList.isEmpty()){
            return  ResultUtil.error("文件内容为空");
        }
        //删除标题
        dataList.remove(0);
        //存储到数据库中
        if(dataList.isEmpty()){
            return  ResultUtil.error("填写题目内容");
        }
        //存储到数据库中
       List<QuestionBan>  questionBanList = dataList.stream().map(List -> {

            QuestionBan questionBan = new QuestionBan();
            questionBan.setDetailsId(detailsId);
            questionBan.setMatter(String.valueOf(List.get(0)));
            questionBan.setQuestionTypes(String.valueOf(List.get(1)).equals("单选") ? "1" : "2");
            questionBan.setAanswer(String.valueOf(List.get(2)));
            questionBan.setBanswer(String.valueOf(List.get(3)));
            questionBan.setCanswer(String.valueOf(List.get(4)));
            questionBan.setDanswer(String.valueOf(List.get(5)));
            questionBan.setOptionalAnswer(String.valueOf(List.get(6)));
            questionBan.setAnalysis(String.valueOf(List.get(7)));
           return questionBan;
        }).collect(Collectors.toList());
        questionBanMapper.insert(questionBanList);
        return ResultUtil.ok();

    }


    public ResultUtil exportExcel(HttpServletResponse response) {
      //  List<QuestionBan> questionBanList = questionBanMapper.selectList("", "10");
       List<QuestionBan> questionBanList = questionBanMapper.selectPage(null,"",10);
//        String filePath = "C:\\Users\\35050\\Desktop\\2.xlsx";
        ExcelWriter writer = ExcelUtil.getWriter();

        writer.addHeaderAlias("matter", "题目");
        writer.addHeaderAlias("questionTypes", "题型");
        writer.addHeaderAlias("aanswer", "A");
        writer.addHeaderAlias("banswer", "B");
        writer.addHeaderAlias("canswer", "C");
        writer.addHeaderAlias("danswer", "D");
        writer.addHeaderAlias("optionalAnswer", "答案");
        writer.addHeaderAlias("analysis", "分析");
        //合并单元格后的标题行，使用默认标题样式
        //writer.merge(1, "题库标题");
        //一次性写出内容，强制输出标题
        writer.setOnlyAlias(true);
        writer.write(questionBanList, true);
        //下载文件到客户端
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        response.setHeader("Content-Disposition", String.format("attachment;filename=%s. xlsx", URLEncodeUtil.encode("题库管理信息")));
        ServletOutputStream out = null;
        try {
            out = response.getOutputStream();
        } catch (IOException e) {
            e.printStackTrace();
            log.error("下载失败，原因：{}", e.getMessage());
        }
        writer.flush(out, true);

        //关闭writer，释放内存
        writer.close();
        IoUtil.close(out);
        return ResultUtil.ok();
    }


}
